package me.znext.learn.android;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.*;
import me.znext.learn.android.db.UserDAO;

import java.util.Calendar;

public class ProfileActivity extends AppCompatActivity {
  private static final int RESULT_LOAD_IMAGE = 1;
  private Storage storage = Storage.getStorage();
  private TextView sexTextView;
  private TextView unameTextView;
  private TextView birthdayTextView;
  private ImageView avatarImageView;
  private UserDAO userDAO;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    this.setTitle("个人信息");
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ListView leftMenu = (ListView) findViewById(R.id.leftMenuList);
    DrawerLayout leftMenuDrawerLayout = (DrawerLayout) findViewById(R.id.leftMenuDrawerLayout);
    new LeftMenu(this, leftMenu, leftMenuDrawerLayout);

    sexTextView = (TextView) findViewById(R.id.sexTextView);
    unameTextView = (TextView) findViewById(R.id.unameTextView);
    birthdayTextView = (TextView) findViewById(R.id.birthdayTextView);

    RelativeLayout unameWrap = (RelativeLayout) findViewById(R.id.unameWrap);
    assert unameWrap != null;
    unameWrap.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        gotoEditProfile("设置姓名", "请输入你的姓名", "uname");
      }
    });
    initProfile();

    RelativeLayout sexWrap = (RelativeLayout) findViewById(R.id.sexWrap);
    assert sexWrap != null;
    sexWrap.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        setSex();
      }
    });

    RelativeLayout birthdayWrap = (RelativeLayout) findViewById(R.id.birthdayWrap);
    assert birthdayWrap != null;
    birthdayWrap.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        setBirthday();
      }
    });

    RelativeLayout avatarWrap = (RelativeLayout) findViewById(R.id.avatarWrap);
    assert avatarWrap != null;
    avatarWrap.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        setAvatar();
      }
    });
    initProfile();
    userDAO = new UserDAO(this);
  }

  @Override
  protected void onResume() {
    super.onResume();
    initProfile();
  }

  private void gotoEditProfile(String title, String hint, String fieldName) {
    Intent intent = new Intent();
    intent.putExtra("title", title);
    intent.putExtra("hint", hint);
    intent.putExtra("fieldName", fieldName);
    intent.setClass(ProfileActivity.this, EditProfileActivity.class);
    startActivity(intent);
  }

  private void initProfile() {
    assert unameTextView != null;
    unameTextView.setText(storage.getProfile("uname"));
    sexTextView.setText(storage.getProfile("sex"));
    birthdayTextView.setText(storage.getProfile("birthday"));
    avatarImageView = (ImageView) findViewById(R.id.avatarImageView);

    String avatarFilePath = storage.getProfile("avatar");
    if (avatarFilePath != null) {
      assert avatarImageView != null;
      avatarImageView.setImageBitmap(BitmapFactory.decodeFile(avatarFilePath));
    }
  }

  private void setSex() {
    Dialog dialog = onCreateDialog();
    dialog.show();
  }

  private Dialog onCreateDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("性别")
      .setItems(R.array.sex_array, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int index) {
          Resources res = getResources();
          String[] sexArray = res.getStringArray(R.array.sex_array);
          String sex = sexArray[index];

          assert sexTextView != null;
          sexTextView.setText(sex);
          userDAO.update(storage.getProfile("uname"), "sex", sex);
          storage.updateProfile("sex", sex);
        }
      });
    return builder.create();
  }

  private void setBirthday() {
    Calendar c = Calendar.getInstance();
    new DatePickerDialog(this,
      new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker dp, int year, int month, int day) {
          String birthday = year + " / " + month + " / " + day;
          birthdayTextView.setText(birthday);
          userDAO.update(storage.getProfile("uname"), "birthday", birthday);
          storage.updateProfile("birthday", birthday);
        }
      },
      c.get(Calendar.YEAR),
      c.get(Calendar.MONTH),
      c.get(Calendar.DAY_OF_MONTH)).show();
  }

  private void setAvatar() {
    Intent i = new Intent(
      Intent.ACTION_PICK,
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
      Uri selectedImage = data.getData();
      String[] filePathColumn = {MediaStore.Images.Media.DATA};

      Cursor cursor = getContentResolver().query(selectedImage,
        filePathColumn, null, null, null);
      assert cursor != null;
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex);
      cursor.close();

      ImageView imageView = (ImageView) findViewById(R.id.avatarImageView);
      assert imageView != null;
      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
      storage.updateProfile("avatar", picturePath);
    }
  }
}
